/*
 * ===========================================================================
 *
 *      Filename: atomic.c
 *   Description: atomaic operation
 *        Author: Ye wenhao, wenhaoye@126.com
 *  Organization: 
 *
 * ===========================================================================
 */
#include "atomic.h"

void atomic_init(atomic_t *self, uint32_t n)
{
    mutex_init(&self->sync);
    self->n = n;
}

void atomic_term(atomic_t *self)
{
    mutex_term(&self->sync);
    self->n = 0;
}

uint32_t atomic_inc(atomic_t *self, uint32_t n)
{
#ifdef ATOMIC_GCC_BUILTINS
    return (uint32_t) __sync_fetch_and_add(&self->n, n);
#elif ATOMIC_MUTEX
    uint32_t res;
    mutex_get(&self->sync);
    res = self->n;
    self->n += n;
    mutex_put(&self->sync);
    return res;
#else
#error
#endif
}

uint32_t atomic_dec(atomic_t *self, uint32_t n)
{
#ifdef ATOMIC_GCC_BUILTINS
    return (uint32_t) __sync_fetch_and_sub(&self->n, n);
#elif ATOMIC_MUTEX
    uint32_t res;
    mutex_get(&self->sync);
    res = self->n;
    self->n -= n;
    mutex_put(&self->sync);
    return res;
#else
#error
#endif
}
